package com.martin.lib_base.utils

import android.app.Activity

/**
 * Activity管理器
 * 可实现连续多个页面的直接返回
 * 也可随时随地的退出程序
 * BaseActivity中已添加addActivity/removeActivity方法,继承自BaseActivity的类要实现上述功能直接使用即可
 */
object FishActivityCollector {
    private val activities = ArrayList<Activity>()

    /**
     * 添加activity
     */
    fun addActivity(activity: Activity) {
        activities.add(activity)
    }

    /**
     * 移除activity
     */
    fun removeActivity(activity: Activity) {
        if (!activity.isFinishing) {
            activity.finish()
        }
        activities.remove(activity)
    }

    /**
     * 获取当前的activity
     */
    fun currentActivity(): Activity {
        val activity = activities.last()
        return activity
    }

    /**
     * 通过clsss类名返回到相应的Activity
     * @clsss : Activity类名
     */
    fun popTopActivities(clsss: Class<*>) {
        while (true) {
            val activity = currentActivity() ?: break
            if (activity.javaClass == clsss) {
                break
            }
            removeActivity(activity)
        }
    }

    /**
     * 销毁所有activity,退出程序
     */
    fun finishAll() {
        for (activity in activities) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
        activities.clear()
    }
}